package com.softserve.crazymachine.response;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mykhailo Tys
 * 
 */
public class ResponseBuilder {
	/**
	 * headers - byte array, which saves byte view of response headers body -
	 * byte array of data of response
	 */
	private byte[] headers;
	private byte[] body;

	/**
	 * @param r
	 *            takes Response object and creates byte array of headers and
	 *            body of response
	 */
	public void buildResponse(Response r) {
		headers = null;
		body = null;
		StringBuilder builder = new StringBuilder();
		builder.append("HTTP/1.1 ");
		builder.append(r.getCode());
		builder.append(" ");
		builder.append(Messages.getMessage(r.getCode()));
		builder.append("\n");
		headers = builder.toString().getBytes();
		body = r.getBody();
	}

	/**
	 * @param r
	 *            takes Response object and creates byte array of headers and
	 *            body of error response
	 */

	public void buildErrorResponse(Response r) {
		headers = null;
		body = null;
		StringBuilder builder = new StringBuilder();
		builder.append("HTTP/1.1 ");
		builder.append(r.getCode());
		builder.append(" ");
		builder.append(Messages.getMessage(r.getCode()));
		builder.append("\n");
		headers = builder.toString().getBytes();
		StringBuilder bodyBuilder = new StringBuilder();
		bodyBuilder.append("<html><head><title>");
		bodyBuilder
				.append(r.getCode() + " " + Messages.getMessage(r.getCode()));
		bodyBuilder.append("</title></head><body><p>ERROR</p></body>");
		bodyBuilder.append("</html>");
		body = bodyBuilder.toString().getBytes();

	}

	/**
	 * @return byte array of response
	 */
	public byte[] getBytes() {
		byte[] bites = new byte[headers.length + body.length];
		for (int i = 0; i < headers.length; i++) {
			bites[i] = headers[i];
		}
		for (int j = headers.length; j < bites.length; j++) {
			bites[j] = body[j];
		}
		return bites;
	}
}
